using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Windows.Forms;

namespace WinFormsApp1
{
    public partial class MedicalRecordForm : Form
    {
        private const string ApiBaseUrl = "http://localhost:5044";
        private readonly HttpClient _httpClient;
        private readonly JsonSerializerOptions _jsonOptions;
        private readonly AppointmentListDto _appointment;
        private MedicalRecordDto? _existingMedicalRecord;

        public MedicalRecordForm(AppointmentListDto appointment, MedicalRecordDto? existingMedicalRecord)
        {
            InitializeComponent();
            _httpClient = new HttpClient { BaseAddress = new Uri(ApiBaseUrl) };
            _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
            _appointment = appointment;
            _existingMedicalRecord = existingMedicalRecord;
            LoadPatientAndAppointmentInfo();
            LoadMedicalRecordData();
        }

        private void LoadPatientAndAppointmentInfo()
        {
            txtCardNumber.Text = _appointment.CardNumber;
            txtPatientName.Text = _appointment.PatientName;
            txtDepartment.Text = _appointment.Department;
            txtDoctorName.Text = _appointment.DoctorName;
            txtVisitDate.Text = _appointment.VisitDate?.ToString("yyyy-MM-dd HH:mm");
            
            // Set patient info fields as read-only
            txtCardNumber.ReadOnly = true;
            txtPatientName.ReadOnly = true;
            txtDepartment.ReadOnly = true;
            txtDoctorName.ReadOnly = true;
            txtVisitDate.ReadOnly = true;
        }

        private void LoadMedicalRecordData()
        {
            if (_existingMedicalRecord != null)
            {
                // 加载病历数据（允许随时编辑，不设置只读）
                txtChiefComplaint.Text = _existingMedicalRecord.ChiefComplaint;
                txtPresentIllness.Text = _existingMedicalRecord.PresentIllness;
                txtPastHistory.Text = _existingMedicalRecord.PastHistory;
                txtDiagnosis.Text = _existingMedicalRecord.Diagnosis;
                txtTreatment.Text = _existingMedicalRecord.Treatment;
                txtPrescription.Text = _existingMedicalRecord.Prescription;
                txtAdvice.Text = _existingMedicalRecord.Advice;
                txtRemarks.Text = _existingMedicalRecord.Remarks;

                // 根据状态显示窗口标题（仅用于显示，不限制编辑）
                if (_existingMedicalRecord.Status == "已完成")
                {
                    this.Text = "编辑病历（已完成）";
                }
                else
                {
                    this.Text = "编辑病历（草稿）";
                }
            }
            else
            {
                this.Text = "新建病历";
            }
        }

        private async System.Threading.Tasks.Task SaveMedicalRecord(string status)
        {
            if (string.IsNullOrWhiteSpace(txtChiefComplaint.Text) || string.IsNullOrWhiteSpace(txtDiagnosis.Text))
            {
                MessageBox.Show("主诉和诊断为必填项。", "验证失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            btnSaveDraft.Enabled = false;
            btnComplete.Enabled = false;

            try
            {
                var command = new CreateMedicalRecordCommand
                {
                    AppointmentId = _appointment.AppintmentId,
                    PatientId = _appointment.PatientId,
                    ChiefComplaint = txtChiefComplaint.Text,
                    PresentIllness = txtPresentIllness.Text,
                    PastHistory = txtPastHistory.Text,
                    Diagnosis = txtDiagnosis.Text,
                    Treatment = txtTreatment.Text,
                    Prescription = txtPrescription.Text,
                    Advice = txtAdvice.Text,
                    Status = status
                };

                var json = JsonSerializer.Serialize(command);
                using var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await _httpClient.PostAsync("api/MedicalRecord/CreateOrUpdate", content);
                response.EnsureSuccessStatusCode();
                var respJson = await response.Content.ReadAsStringAsync();
                var apiResult = JsonSerializer.Deserialize<ApiResult<int>>(respJson, _jsonOptions);

                if (apiResult != null && apiResult.Code == 100)
                {
                    string message = status == "草稿" ? "病历草稿保存成功！" : "病历已完成并保存成功！";
                    MessageBox.Show(message, "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    MessageBox.Show($"病历保存失败：{apiResult?.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"请求失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                btnSaveDraft.Enabled = true;
                btnComplete.Enabled = true;
            }
        }

        private async void btnSaveDraft_Click(object? sender, EventArgs e)
        {
            await SaveMedicalRecord("草稿");
        }

        private async void btnComplete_Click(object? sender, EventArgs e)
        {
            await SaveMedicalRecord("已完成");
        }

        private void btnCancel_Click(object? sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        // DTOs
        private class CreateMedicalRecordCommand
        {
            public int AppointmentId { get; set; }
            public int PatientId { get; set; }
            public string? ChiefComplaint { get; set; }
            public string? PresentIllness { get; set; }
            public string? PastHistory { get; set; }
            public string? Diagnosis { get; set; }
            public string? Treatment { get; set; }
            public string? Prescription { get; set; }
            public string? Advice { get; set; }
            public string? Status { get; set; }
        }

        private class ApiResult<T>
        {
            public int Code { get; set; }
            public string? Message { get; set; }
            public T? Data { get; set; }
        }
    }

    // Shared DTOs (moved outside the Form class for accessibility)
    public class AppointmentListDto
    {
        public int AppintmentId { get; set; }
        public string? RegistrationNum { get; set; }
        public string? AppointmentType { get; set; }
        public string? DoctorName { get; set; }
        public string? Department { get; set; }
        public DateTime? VisitDate { get; set; }
        public string? RecordStatus { get; set; }
        public int PatientId { get; set; }
        public string? CardNumber { get; set; }
        public string? PatientName { get; set; }
        public bool Gender { get; set; }
        public int? Age { get; set; }
        public string? Phone { get; set; }
    }

    public class MedicalRecordDto
    {
        public int RecordId { get; set; }
        public int AppointmentId { get; set; }
        public int PatientId { get; set; }
        public string? DoctorName { get; set; }
        public string? Department { get; set; }
        public string? ChiefComplaint { get; set; }
        public string? PresentIllness { get; set; }
        public string? PastHistory { get; set; }
        public string? Diagnosis { get; set; }
        public string? Treatment { get; set; }
        public string? Prescription { get; set; }
        public string? Advice { get; set; }
        public string? Remarks { get; set; }
        public DateTime? VisitDate { get; set; }
        public DateTime CreateTime { get; set; }
        public DateTime? UpdateTime { get; set; }
        public string? Status { get; set; }
        public string? PatientName { get; set; }
        public string? CardNumber { get; set; }
        public bool PatientGender { get; set; }
        public int? PatientAge { get; set; }
    }
}
